﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Web;
using GPMS.Model;
using System.Web.Security;
using System.Data;
using System.Web.Mvc;

namespace GPMS.BLL
{
    public static class AccountHelper
    {

        /// <summary>
        /// 检查是否登陆
        /// </summary>
        /// <param name="context"></param>
        /// <returns></returns>
        public static bool IsLogin(HttpContextBase context)
        {
            return context.User.Identity.IsAuthenticated;
        }

        /// <summary>
        /// 登陆
        /// </summary>
        /// <param name="user"></param>
        /// <param name="gpms"></param>
        /// <param name="response"></param>
        /// <returns></returns>
        public static bool SignIn(LoginVM model, HttpResponseBase response,ExtendedGPMSDb gpmsDb)
        {
            var users = gpmsDb.UserInfos.Where(SelectParameter(model));
            if (users.Count() > 0)
            {
                FormsAuthenticationTicket ticket = new FormsAuthenticationTicket(
                    1,
                    users.FirstOrDefault().UserName,
                    DateTime.Now,
                    DateTime.Now.AddDays(7),
                    true,
                    users.FirstOrDefault().UserID.ToString(),
                    FormsAuthentication.FormsCookiePath);
                //response.SetCookie(new HttpCookie(FormsAuthentication.FormsCookieName,
                //    FormsAuthentication.Encrypt(ticket)));
                response.Cookies.Add(new HttpCookie(FormsAuthentication.FormsCookieName,
                    FormsAuthentication.Encrypt(ticket)) { Path=FormsAuthentication.FormsCookiePath});
                return true;
            }
            else
            {
                return false;
            }
        }
        public static Guid GetLoginUserID(HttpRequestBase Request)
        {
            HttpCookie cookie = Request.Cookies.Get(FormsAuthentication.FormsCookieName);
            return cookie == null ? Guid.Empty : Guid.Parse(FormsAuthentication.Decrypt(cookie.Value).UserData);
        }
        public static UserInfo GetLoginUser(HttpRequestBase Request, ExtendedGPMSDb db)
        {
            Guid userid = GetLoginUserID(Request);

            return db.UserInfos.FirstOrDefault(u => u.UserID == userid);
        }

        private static Func<UserInfo, bool> SelectParameter(LoginVM model)
        {
            Func<UserInfo, bool> func;
            Func<UserInfo, bool> funcCommon = user =>
                user.Password == model.Password &&
                user.IsDeleted == false &&
                user.IsLocked == false;
            if (model.LoginType.Equals("userName"))
            {
                func = user => user.UserName == model.User && funcCommon(user);
            }
            else
            {
                func = user => user.UserIdentity == model.User && funcCommon(user);
            }
            return func;
        }

        /// <summary>
        /// 登出
        /// </summary>
        public static void SignOut()
        {
            FormsAuthentication.SignOut();
        }

        /// <summary>
        /// 获得用户信息
        /// </summary>
        /// <param name="id">用户id</param>
        /// <returns></returns>
        public static UserInfo Get(Guid id,ExtendedGPMSDb gpmsDb)
        {

            return gpmsDb.UserInfos.Where(u => u.UserID == id).FirstOrDefault();
        }
        public static UserInfo Get(string name, ExtendedGPMSDb gpmsDb)
        {

            return gpmsDb.UserInfos.FirstOrDefault(u => u.UserName == name && u.IsDeleted==false);
        }

        /// <summary>
        /// 添加用户
        /// </summary>
        /// <param name="user"></param>
        /// <returns></returns>
        public static void Add(UserInfo user, ExtendedGPMSDb gpmsDb)
        {
            if (user.UserID == Guid.Empty)
            {
                user.UserID = Guid.NewGuid();
            }
            if (gpmsDb.UserInfos.Any(u=>u.UserName==user.UserName))
            {
                throw new DuplicateException("用户名重复");
            }
            user.CreateDate = DateTime.Now;
            user.IsDeleted = false;
            gpmsDb.UserInfos.AddObject(user);
            gpmsDb.SaveChanges();

            user = gpmsDb.UserInfos.First(u => u.UserID == user.UserID);
            gpmsDb.Roles.Where(r => r.IsDefault == true && r.IsDeleted == false).ToList().ForEach(r => user.Roles.Add(r));
            gpmsDb.SaveChanges();
        }

        /// <summary>
        /// 删除用户
        /// </summary>
        /// <param name="id"></param>
        public static void Delete(Guid id, ExtendedGPMSDb gpmsDb)
        {
            UserInfo user = Get(id, gpmsDb);
            user.IsDeleted = true;
            gpmsDb.SaveChanges();
        }

        public static AccountVM GetAccountVM(ExtendedGPMSDb gpmsDb)
        {
            return new AccountVM()
            {
                User = new UserInfo(),
                Specialties = gpmsDb.Specialties.ToList()
            };
        }

        public static List<UserInfo> GetList(ExtendedGPMSDb gpmsDb)
        {
            return gpmsDb.UserInfos.Where(u => u.IsDeleted == false).ToList();
        }

        /// <summary>
        /// 获得用户角色列表
        /// </summary>
        /// <param name="id"></param>
        /// <param name="gpmsDb"></param>
        /// <returns></returns>
        public static List<UserRoleVM> GetUserRole(Guid id, ExtendedGPMSDb gpmsDb)
        {
            return gpmsDb.Roles
                .Where(r => r.IsDeleted == false)
                .Select(r => new UserRoleVM
                {
                    Role = r,
                    Permission = r.Users.Any(u => u.UserID == id)
                }).ToList();
        }

        public static List<UserRoleVM> GetUserRole(ExtendedGPMSDb gpmsDb)
        {
            return gpmsDb.Roles
                .Where(r => r.IsDeleted == false)
                .Select(r => new UserRoleVM
                {
                    Role = r,
                    Permission = false
                }).ToList();
        }

        /// <summary>
        /// 保存用户角色信息
        /// </summary>
        /// <param name="id"></param>
        /// <param name="collection"></param>
        /// <param name="gpmsDb"></param>
        public static void SaveUserRole(Guid id, FormCollection collection, ExtendedGPMSDb gpmsDb)
        {
            List<UserRoleVM> permission = GetUserRole(id, gpmsDb);
            foreach (var item in collection.AllKeys)
            {
                permission.SingleOrDefault(p => p.Role.RoleID == Guid.Parse(item))
                    .Permission = (bool)collection.GetValue(item).ConvertTo(typeof(bool));
            }
            permission.ForEach(p =>
                {
                    UserInfo user = gpmsDb.UserInfos.FirstOrDefault(u => u.UserID == id);
                    bool contain = gpmsDb.Roles
                        .FirstOrDefault(r => r.RoleID == p.Role.RoleID)
                        .Users
                        .Contains(user);
                    if (p.Permission && !contain)
                    {
                        user.Roles.Add(p.Role);
                    }
                    else if (!p.Permission && contain)
                    {
                        user.Roles.Remove(p.Role);
                    }
                });
            gpmsDb.SaveChanges();
        }

       

        public static string GetUserRoleStr(HttpRequestBase Request, ExtendedGPMSDb db)
        {
            StringBuilder sb = new StringBuilder();
            Guid userid = GetLoginUserID(Request);
            db.Roles
                .Where(r => r.Users.Any(u => u.UserID == userid) && !r.IsDeleted && r.Display)
                .ToList().ForEach(r => sb.Append(r.RoleName + ","));
            string role = sb.Length > 1 ? sb.ToString().Substring(0, sb.Length - 1) : string.Empty;
            role += " " + db.UserInfos.First(u => u.UserID == userid).RealName;
            return role;
        }

        public static Guid GetLonginUserSpecialty(HttpRequestBase Request, ExtendedGPMSDb db)
        {
            Guid userid = GetLoginUserID(Request);
            return db.UserInfos.FirstOrDefault(u => u.UserID == userid).SpecialtyID;
        }

        public static List<UserInfo> GetTeachers(HttpRequestBase Request, ExtendedGPMSDb db)
        {
            Guid teacher= SettingHelper.Get(db).TeacherRole;
            Guid specialtyID=GetLonginUserSpecialty(Request,db);
            return db.UserInfos
                .Where(u => u.Roles.Any(r => r.RoleID == teacher) && u.SpecialtyID == specialtyID)
                .ToList();
        }

        public static List<UserInfo> GetStudents(HttpRequestBase Request, ExtendedGPMSDb db)
        {
            Guid student = SettingHelper.Get(db).StudentRole;
            Guid specialtyID = GetLonginUserSpecialty(Request, db);
            return db.UserInfos
                .Where(u => u.Roles.Any(r => r.RoleID == student) && u.SpecialtyID == specialtyID)
                .ToList();
        }

    }
}
